/*
 * @Author: taoyuqing
 * @Date: 2023-01-09 22:17:16
 * @Description: 登录页
 */
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_svg/svg.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:spree/utils/api.dart';
import 'package:spree/widgets/common_container.dart';

import '../../provider/model/user_model.dart';

class RegisterPage extends StatefulWidget {
  final Function? onLogin;
  RegisterPage({Key? key, this.onLogin}) : super(key: key);

  @override
  State<RegisterPage> createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  TextEditingController _pwdCtro = TextEditingController();
  TextEditingController _nameCtro = TextEditingController();
  TextEditingController _emailCtro = TextEditingController();
  TextEditingController _inviteCodeCtro = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('register'),
      ),
      body: CommonContainer(
        child: ListView(
          padding: EdgeInsets.only(top: 100),
          children: [
            SvgPicture.asset(
              'images/BETSPREELOGO.svg',
              width: 200,
            ),
            Container(
              margin: EdgeInsets.only(top: 20),
              padding: EdgeInsets.only(left: 20, right: 20),
              decoration: BoxDecoration(
                  borderRadius: const BorderRadius.all(Radius.circular(8.0)),
                  border: Border.all(
                      width: 1, color: Color.fromRGBO(255, 255, 255, 0.5))),
              child: TextField(
                style: TextStyle(color: Colors.white),
                cursorColor: Colors.white,
                decoration: InputDecoration(
                    icon: Icon(
                      Icons.account_circle_outlined,
                      color: Color.fromRGBO(255, 255, 255, 0.5),
                    ),
                    hintText: 'Enter your Username',
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                      color: Color.fromRGBO(255, 255, 255, 0.7),
                    )),
                controller: _nameCtro,
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: 20),
              padding: EdgeInsets.only(left: 20, right: 20),
              decoration: BoxDecoration(
                  borderRadius: const BorderRadius.all(Radius.circular(8.0)),
                  border: Border.all(
                      width: 1, color: Color.fromRGBO(255, 255, 255, 0.5))),
              child: TextField(
                style: TextStyle(color: Colors.white),
                cursorColor: Colors.white,
                decoration: InputDecoration(
                    suffix: Icon(
                      Icons.remove_red_eye_outlined,
                      color: Color.fromRGBO(255, 255, 255, 0.5),
                    ),
                    icon: Icon(
                      Icons.lock,
                      color: Color.fromRGBO(255, 255, 255, 0.5),
                    ),
                    hintText: 'Enter your Email',
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                      color: Color.fromRGBO(255, 255, 255, 0.7),
                    )),
                controller: _emailCtro,
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: 20),
              padding: EdgeInsets.only(left: 20, right: 20),
              decoration: BoxDecoration(
                  borderRadius: const BorderRadius.all(Radius.circular(8.0)),
                  border: Border.all(
                      width: 1, color: Color.fromRGBO(255, 255, 255, 0.5))),
              child: TextField(
                style: TextStyle(color: Colors.white),
                cursorColor: Colors.white,
                decoration: InputDecoration(
                    suffix: Icon(
                      Icons.remove_red_eye_outlined,
                      color: Color.fromRGBO(255, 255, 255, 0.5),
                    ),
                    icon: Icon(
                      Icons.lock,
                      color: Color.fromRGBO(255, 255, 255, 0.5),
                    ),
                    hintText: 'Enter your password',
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                      color: Color.fromRGBO(255, 255, 255, 0.7),
                    )),
                obscureText: true,
                controller: _pwdCtro,
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: 20),
              padding: EdgeInsets.only(left: 20, right: 20),
              decoration: BoxDecoration(
                  borderRadius: const BorderRadius.all(Radius.circular(8.0)),
                  border: Border.all(
                      width: 1, color: Color.fromRGBO(255, 255, 255, 0.5))),
              child: TextField(
                style: TextStyle(color: Colors.white),
                cursorColor: Colors.white,
                decoration: InputDecoration(
                    hintText: 'Invite Code (Optional)',
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                      color: Color.fromRGBO(255, 255, 255, 0.7),
                    )),
                controller: _inviteCodeCtro,
              ),
            ),
            Container(
              height: 50,
              margin: EdgeInsets.only(top: 20),
              child: ElevatedButton(
                  style: ButtonStyle(
                    backgroundColor:
                        MaterialStateProperty.all(Color(0xFFF93967)),
                  ),
                  onPressed: () {
                    if (widget.onLogin != null) {
                      widget.onLogin!();
                    }
                    _handleRegister();
                  },
                  child: Text(
                    'Register',
                    style: TextStyle(fontSize: 16),
                  )),
            ),
          ],
        ),
      ),
    );
  }

  _handleRegister() async {
    bool check = checkForm();
    if (!check) {
      return;
    }
    Map params = {
      'nickName': _nameCtro.text,
      'email': _emailCtro.text,
      'passWord': _pwdCtro.text,
      'registerInvitationCode': _inviteCodeCtro.text
    };

    try {
      dynamic user = await Api.regist(params);

      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('accessToken', user['data']['accessToken']);
      if (prefs.get('accessToken') != null && prefs.get('accessToken') != '') {
        dynamic userInfoData = await Api.getInfo();
        dynamic userInfo = userInfoData['data'];
        dynamic userAccount = await Api.account();
        Provider.of<UserModel>(context, listen: false).setUserInfo(
            name: '${userInfo['nickname']}',
            id: '${userInfo['userId']}',
            mail: '${userInfo['email']}',
            imgUrl: '${userInfo['avatar']}',
            level: '${userInfo['vipLevel']}',
            token: user['data']['accessToken'],
            amount: '${userAccount['data']['accountAmount']}');
        await prefs.setString('userId', '${userInfoData['data']['userId']}');
        await prefs.setString('userName', _nameCtro.text);
        await prefs.setString('passWord', _pwdCtro.text);
      }

      await EasyLoading.showSuccess(
        '注册成功',
      );
      Navigator.pushNamed(context, 'ProfilePage');
    } catch (e) {
      print(e);
      EasyLoading.showError('');
    }
  }

  bool checkForm() {
    bool result = true;
    int maxLen = 20;
    int minLen = 8;
    String regexEmail =
        "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}\$";

    String name = _nameCtro.text;
    String email = _emailCtro.text;
    String pwd = _pwdCtro.text;
    String inviteCode = _inviteCodeCtro.text;
    //校验name最大长度
    if (name == '') {
      EasyLoading.showError("user name is required");
      result = false;
      return result;
    } else {
      if (name.length >= maxLen) {
        EasyLoading.showError("user name max length is $maxLen");
        result = false;
        return result;
      }
    }

    if (email == '') {
      print(email);
      EasyLoading.showError("email is required");
      result = false;
      return result;
    } else {
      if (!new RegExp(regexEmail).hasMatch(email)) {
        EasyLoading.showError("please type in correct email");
        result = false;
        return result;
      }
    }
    if (pwd == '') {
      EasyLoading.showError("password is required");
      result = false;
      return result;
    } else {
      if (pwd.length < minLen) {
        EasyLoading.showError("password length required at least $minLen");
        result = false;
        return result;
      }
      if (pwd.length > maxLen) {
        EasyLoading.showError("password  max length is $maxLen");
        result = false;
        return result;
      }
    }
    return result;
  }
}
